<?php
/**
 * Date: 2021/2/22
 * Note: 将store/update表单校验放在Controller里, 放弃 App\Http\Request, 减小工作量
 */

namespace App\Http\Controllers\Admin;

use App\Caches\RoleCache;
use App\Http\Controllers\Controller;
use App\Models\Game\Center\MallMarketRebate;
use App\Models\Manager;
use App\Services\AccountOperateLogService;
use Illuminate\Http\Request;

class BackendController extends Controller
{
    /**
     * 当前登录用户(管理员)
     * @var Manager $user
     */
    protected Manager $user;

    /**
     * 允许的渠道
     * @var array
     */
    protected array $allowSources = [];

    /**
     * BaseController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->middleware(function($request, $next) {
            $user = $request->user();
            if ($user) {
                $this->user = $user;
                $this->getAllowSources();
            }
            return $next($request);
        });
    }

    /**
     * 其它控制器调用时, 需要用户信息的, 调用此方法
     * @param Request $request
     * @return $this
     */
    public function setUser(Request $request)
    {
        $user = $request->user();
        if ($user) {
            $this->user = $user;
            $this->getAllowSources();
        }
        return $this;
    }

    /**
     * @return Manager|mixed
     */
    public function getUser()
    {
        if ($this->user->id) return $this->user;
        $this->user = request()->user();
        return $this->user;
    }

    /**
     * 获取可使用的渠道
     * 需要根据渠道处理的数据, 应从此获取可用渠道列表
     */
    private function getAllowSources()
    {
        // 用户自身的渠道
        $this->allowSources = $this->user->sources ?: [];
        // 未设置, 使用角色渠道
        if (!$this->allowSources) {
            foreach ($this->user->role as $roleId) {
                $roleCache = RoleCache::get($roleId);
                $this->allowSources = array_merge($this->allowSources, $roleCache['sources'] ?? []);
            }
        }
        $this->allowSources = array_unique($this->allowSources);
    }
}
